import { errorCleanUnUpload } from 'src/api/dataCenter';
import { errorCleanUnUpload as errorCleanFeatureSetUpload } from 'src/api/featureSet';
import {
  PLATFORM_UPLOAD_ERROR_QUEUE,
  PLATFORM_UPLOAD_FEATURE_SET_ERROR_QUEUE,
} from 'src/utils/consts';
import { usePlatformFeatureSetUploadStore } from 'stores/platform-featureset-upload';
import { usePlatformUploadStore } from 'stores/platform-upload';
import { onMounted } from 'vue';

const platformUploadStore = usePlatformUploadStore();
const platformFeatureSetUploadStore = usePlatformFeatureSetUploadStore();

export const useCleanErrorUploadQueue = (type: 'dataset' | 'featureSet') => {
  onMounted(async () => {
    const Constant =
      type === 'dataset'
        ? PLATFORM_UPLOAD_ERROR_QUEUE
        : PLATFORM_UPLOAD_FEATURE_SET_ERROR_QUEUE;
    const uploadErrorQueueRecord = localStorage.getItem(Constant);
    let errorIds: number[] = [];
    let queue: Record<string, number[]> = {};
    if (uploadErrorQueueRecord) {
      queue = JSON.parse(uploadErrorQueueRecord) as Record<string, number[]>;
      Object.keys(queue).forEach((key) => {
        errorIds = [...errorIds, ...queue[key]];
      });
    }
    if (!errorIds.length) return;
    const errorIdsSet = [...new Set(errorIds)];
    errorIdsSet.map(async (errorId) => {
      if (type == 'dataset') {
        try {
          await errorCleanUnUpload(errorId);
          platformUploadStore.excludeErrorId(errorId);
          await Promise.all([
            platformUploadStore.refreshDatasetList(),
            platformUploadStore.initPlatformUploadList(),
          ]);
        } catch (e: any) {}
      } else {
        try {
          await errorCleanFeatureSetUpload(String(errorId));
          platformFeatureSetUploadStore.excludeErrorId(String(errorId));
          await Promise.all([
            platformFeatureSetUploadStore.refreshFeatureSetList(),
            platformFeatureSetUploadStore.initPlatformUploadList(),
          ]);
        } catch (e: any) {}
      }
    });
  });
};
